package logic

import (
	"context"
	"fmt"
	"mores/models/cache"
	"mores/models/mysql"

	"mores/moresrpc/internal/svc"
	"mores/moresrpc/moresrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetPasswordLogic {
	return &ForgetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ForgetPasswordLogic) ForgetPassword(in *moresrpc.ForgetPasswordRequest) (*moresrpc.ForgetPasswordResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.Rdb.Get(l.ctx, "captcha").Result()

	if result != in.CaptchaCode {
		return nil, fmt.Errorf("图形验证码错误")
	}
	s, _ := cache.Rdb.Get(l.ctx, "sendSms").Result()
	if s != in.SendSmsCode {
		return nil, fmt.Errorf("短信验证码错误")
	}
	var FindUser mysql.User
	mysql.DB.Debug().Where("account=?", in.Account).Find(&FindUser)

	if FindUser.ID == 0 {
		return nil, fmt.Errorf("账号不存在,请前去注册")
	}
	if in.Password != in.NewPassword {
		return nil, fmt.Errorf("原密码与新密码不一致,请重新输入")
	}
	if FindUser.Password == in.Password {
		return nil, fmt.Errorf("两次密码一致,请重新输入")
	}
	FindUser.Password = in.Password
	return &moresrpc.ForgetPasswordResponse{
		UserId: int64(FindUser.ID),
	}, nil
}
